import { memo, useEffect, useState } from "react";
import StudentSContentstyle from "./style";
import { useGetStudents } from "../../../../service/student";
import { StudentType } from "../../../../graphql/student";
import { Col, Empty, Pagination, Row, Spin } from "antd";
import StudentCard from "../studentCard";
import { shallowEqual, useSelector } from "react-redux";
import { RootState } from "../../../../store";

const StudentContent = memo((props: {
  name: string,
  setDrawerOpen: (open: boolean) => void,
  setStudentData: (data: StudentType) => void
}) => {
  const { name, setStudentData, setDrawerOpen } = props;
  const [data, setData] = useState<StudentType[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalNum, setTotalNum] = useState(1);
  const { getStudents, loading } = useGetStudents();
  const { org } = useSelector((state: RootState) => (
    {
      org: state.orgReducer.currentOrg
    }
  ), shallowEqual);

  useEffect(() => {
    if (name) {
      setCurrentPage(1);
    }
    void getStudents(12, currentPage, org.id, name).then((res) => {
      setData(res?.data!);
      setTotalNum(res?.page.total!);
    });
  }, [name, currentPage, org]);

  const handelPaginationChange = (value: number) => {
    setCurrentPage(value);
  };
  return (
    <StudentSContentstyle>
      {!loading ? (
        totalNum === 0 ? (
          <Empty description="暂无学员信息" />
        ) : (
          <div className="contentCenter">
            <Row gutter={15}>
              {data?.map((item) => (
                <Col span={4} key={item.id}>
                  <StudentCard setDrawerOpen={setDrawerOpen} setStudentData={setStudentData} data={item} />
                </Col>
              ))}
            </Row>
            <Pagination
              total={totalNum}
              pageSize={12}
              current={currentPage}
              showTotal={(total, range) => {
                return `第${range[0]}-${range[1]}条/总共${total}条`;
              }}
              onChange={(value) => handelPaginationChange(value)}
            />
          </div>
        )
      ) : (
        <Spin size="large" />
      )}
    </StudentSContentstyle>
  );
});

export default StudentContent;
